package com.example.ymm.util;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.time.*;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.*;

/**
 * Created by Administrator on 2017/3/10 010.
 */
@Slf4j
public class DateKit {
   // Logger logger = LogUtils.getExceptionLogger();
    public static final int INTERVAL_DAY = 1;
    public static final int INTERVAL_WEEK = 2;
    public static final int INTERVAL_MONTH = 3;
    public static final int INTERVAL_YEAR = 4;
    public static final int INTERVAL_HOUR = 5;
    public static final int INTERVAL_MINUTE = 6;
    public static final int INTERVAL_SECOND = 7;
    public static final Date tempDate = new Date((new Long("-2177481952000")).longValue());
    private static List<SimpleDateFormat> dateFormats = new ArrayList(12) {
        private static final long serialVersionUID = 2249396579858199535L;

        {
            this.add(new SimpleDateFormat("yyyy-MM-dd"));
            this.add(new SimpleDateFormat("yyyy/MM/dd"));
            this.add(new SimpleDateFormat("yyyy.MM.dd"));
            this.add(new SimpleDateFormat("yyyy-MM-dd HH:24:mm:ss"));
            this.add(new SimpleDateFormat("yyyy/MM/dd HH:24:mm:ss"));
            this.add(new SimpleDateFormat("yyyy.MM.dd HH:24:mm:ss"));
            this.add(new SimpleDateFormat("M/dd/yyyy"));
            this.add(new SimpleDateFormat("dd.M.yyyy"));
            this.add(new SimpleDateFormat("M/dd/yyyy hh:mm:ss a"));
            this.add(new SimpleDateFormat("dd.M.yyyy hh:mm:ss a"));
            this.add(new SimpleDateFormat("dd.MMM.yyyy"));
            this.add(new SimpleDateFormat("dd-MMM-yyyy"));
        }
    };

    public DateKit() {
    }

    public static boolean isToday(Date date) {
        Date now = new Date();
        boolean result = true;
        result &= date.getYear() == now.getYear();
        result &= date.getMonth() == now.getMonth();
        result &= date.getDate() == now.getDate();
        return result;
    }

    public static long DaysBetween(Date date1, Date date2) {
        if(date2 == null) {
            date2 = new Date();
        }

        long day = (date2.getTime() - date1.getTime()) / 86400000L;
        return day;
    }

    public static boolean compareDate(String date1, String date2) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

        try {
            Date e = format.parse(date1);
            Date d2 = format.parse(date2);
            return !e.after(d2);
        } catch (ParseException var5) {
            var5.printStackTrace();
            return false;
        }
    }

    public static Date dateFormat(String date, String dateFormat) {
        if(date == null) {
            return null;
        } else {
            SimpleDateFormat format = new SimpleDateFormat(dateFormat);
            try {
                return format.parse(date);
            } catch (Exception ignored) {
                return null;
            }

        }
    }

    public static Date dateFormat(String date) {
        return dateFormat(date, "yyyy-MM-dd HH:mm:ss");
    }

    public static Date dateFormatNotSecond(String date) {
        return dateFormat(date, "yyyy-MM-dd HH:mm");
    }

    public static Date shortDateFormat(String date) {
        return dateFormat(date, "yyyy-MM-dd");
    }

    public static String dateFormat(Date date, String dateFormat) {
        if(date != null) {
            SimpleDateFormat format = new SimpleDateFormat(dateFormat);
            return format.format(date);
        }

        return "";
    }

    public static String birthdayFormat(Date date) {
        if(date != null) {
            SimpleDateFormat format = null;
            if(date.before(tempDate)) {
                format = new SimpleDateFormat("MM-dd");
            } else {
                format = new SimpleDateFormat("yyyy-MM-dd");
            }
            return format.format(date);
        }

        return "";
    }

    public static String dateFormat(Date date) {
        return dateFormat(date, "yyyy-MM-dd HH:mm:ss");
    }

    public static boolean isExpiredDay(Date date1) {
        long day = ((new Date()).getTime() - date1.getTime()) / 86400000L;
        return day >= 1L;
    }

    /**
     * 获取昨天 date
     * yyyy-MM-dd
     * @return
     */
    public static Date getYesterday() {
        Date date = new Date();
        long time = date.getTime() / 1000L - 86400L;
        date.setTime(time * 1000L);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

        try {
            date = format.parse(format.format(date));
        } catch (Exception var5) {
            System.out.println(var5.getMessage());
        }

        return date;
    }



    public static Date getYesterdayYmd() {
        Date date = new Date();
        long time = date.getTime() / 1000L - 86400L;
        date.setTime(time * 1000L);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

        try {
            date = format.parse(format.format(date));
        } catch (Exception var5) {
            System.out.println(var5.getMessage());
        }

        return date;
    }

    public static Date getYesterdayYmd(Date date) {
        long time = date.getTime() / 1000L - 86400L;
        date.setTime(time * 1000L);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

        try {
            date = format.parse(format.format(date));
        } catch (Exception var5) {
            System.out.println(var5.getMessage());
        }

        return date;
    }

    public static Date getWeekAgo() {
        Date date = new Date();
        long time = date.getTime() / 1000L - 604800L;
        date.setTime(time * 1000L);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

        try {
            date = format.parse(format.format(date));
        } catch (Exception var5) {
            System.out.println(var5.getMessage());
        }

        return date;
    }

    public static String getDaysAgoString(int interval) {
        Date date = new Date();
        long time = date.getTime() / 1000L - (long)(interval * 60 * 60 * 24);
        date.setTime(time * 1000L);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

        try {
            return format.format(date);
        } catch (Exception var6) {
            System.out.println(var6.getMessage());
            return "";
        }
    }

    public static Date getDaysAgo(int interval) {
        Date date = new Date();
        long time = date.getTime() / 1000L - (long)(interval * 60 * 60 * 24);
        date.setTime(time * 1000L);
        return date;
    }


    public static Date getTomorrow() {
        Date date = new Date();
        long time = date.getTime() / 1000L + 86400L;
        date.setTime(time * 1000L);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

        try {
            date = format.parse(format.format(date));
        } catch (Exception var5) {
            System.out.println(var5.getMessage());
        }

        return date;
    }

    public static Date getBeforeDate(String range) {
        Calendar today = Calendar.getInstance();
        if("week".equalsIgnoreCase(range)) {
            today.add(4, -1);
        } else if("month".equalsIgnoreCase(range)) {
            today.add(2, -1);
        } else {
            today.clear();
        }

        return today.getTime();
    }

    public static Date getThisWeekStartTime() {
        Calendar today = Calendar.getInstance();
        today.set(7, today.getFirstDayOfWeek());
        Calendar weekFirstDay = Calendar.getInstance();
        weekFirstDay.clear();
        weekFirstDay.set(1, today.get(1));
        weekFirstDay.set(2, today.get(2));
        weekFirstDay.set(5, today.get(5));
        return weekFirstDay.getTime();
    }

    /**
     * 获取这个月第一天的日期
     * @return
     */
    public static String getThisMonthStartDate() {
        LocalDate today = LocalDate.now();
        LocalDate firstDayOfMonth = today.withDayOfMonth(1);

        int year = firstDayOfMonth.getYear();
        int month = firstDayOfMonth.getMonthValue();
        int day = firstDayOfMonth.getDayOfMonth();

        String firstDayOfMonthStr = year + "-" + (month<10?"0"+month:month) + "-" + (day<10?"0"+day:day);
        return firstDayOfMonthStr;
    }


    /**
     * 获取 下个月 的日期
     * @return
     */
    public static String getNextMonthStartDate(String startDate) {
        Date date = dateFormat(startDate);
        Instant instant = date.toInstant();
        ZoneId zone = ZoneId.systemDefault();
        LocalDate today = instant.atZone(zone).toLocalDate();
        LocalDate firstDayOfMonth = today.plusMonths(1);

        int year = firstDayOfMonth.getYear();
        int month = firstDayOfMonth.getMonthValue();
        int day = firstDayOfMonth.getDayOfMonth();

        String firstDayOfMonthStr = year + "-" + (month<10?"0"+month:month) + "-" + (day<10?"0"+day:day);
        return firstDayOfMonthStr;
    }

    /**
     * 获取 下个月 1号 的日期
     * @return
     */
    public static String getFirstDayOfNextMonth(String dateTimeStr) {
        DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 解析输入的时间字符串为LocalDateTime对象
        LocalDateTime dateTime = LocalDateTime.parse(dateTimeStr, FORMATTER);
        // 获取下个月的1号0点0分
        LocalDateTime firstDayOfNextMonth = dateTime.plusMonths(1)
                .withDayOfMonth(1)
                .withHour(0)
                .withMinute(0)
                .withSecond(0)
                .withNano(0);

        // 格式化为指定格式的字符串并返回
        return firstDayOfNextMonth.format(FORMATTER);
    }

    /**
     * 获取这个月最后一天的日期
     * @return
     */
    public static String getThisMonthEndDate() {
        LocalDate today = LocalDate.now(); // 获取当前日期
        LocalDate lastDayOfMonth = today.with(TemporalAdjusters.lastDayOfMonth()); // 获取本月最后一天


        int year = lastDayOfMonth.getYear();
        int month = lastDayOfMonth.getMonthValue();
        int day = lastDayOfMonth.getDayOfMonth();

        String firstDayOfMonthStr = year + "-" + (month<10?"0"+month:month) + "-" + (day<10?"0"+day:day);
        return firstDayOfMonthStr;
    }



    /**
     * 获取今年第一天的日期
     * @return
     */
    public static String getThisYearStartDate() {
        LocalDate today = LocalDate.now();
        LocalDate firstDayOfMonth = today.withDayOfMonth(1);

        int year = firstDayOfMonth.getYear();
//        int month = firstDayOfMonth.getMonthValue();
//        int day = firstDayOfMonth.getDayOfMonth();

        String firstDayOfMonthStr = year + "-" +"01" + "-" + "01";
        return firstDayOfMonthStr;
    }

    public static String getToday(String format) {
        String result = "";

        try {
            Date today = new Date();
            SimpleDateFormat simpleFormat = new SimpleDateFormat(format);
            result = simpleFormat.format(today);
        } catch (Exception var4) {
            ;
        }

        return result;
    }

    public static Date getStartDay(int year, int month) {
        Calendar today = Calendar.getInstance();
        today.clear();
        today.set(1, year);
        today.set(2, month - 1);
        today.set(5, 1);
        return today.getTime();
    }

    public static List<Integer> getBeforeYearList(int before) {
        Calendar today = Calendar.getInstance();
        int theYear = today.get(1);
        ArrayList list = new ArrayList();

        for(int i = before; i >= 0; --i) {
            list.add(Integer.valueOf(theYear - i));
        }

        return list;
    }

    /**
     * 根据传入日期推移到某一天
     * interval 1.相差天数 2.相差几周 3.相差几个月 4.相差几年 5.相差几小时 6.相差几分钟 7 相差几秒
     * @param interval
     * @param date
     * @param n
     * @return
     */
    public static Date dateAdd(int interval, Date date, int n) {
        long time = date.getTime() / 1000L;
        switch(interval) {
            case 1:
                time += (long)(n * 86400);
                break;
            case 2:
                time += (long)(n * 604800);
                break;
            case 3:
                time += (long)(n * 2678400);
                break;
            case 4:
                time += (long)(n * 31536000);
                break;
            case 5:
                time += (long)(n * 3600);
                break;
            case 6:
                time += (long)(n * 60);
                break;
            case 7:
                time += (long)n;
        }

        Date result = new Date();
        result.setTime(time * 1000L);
        return result;
    }

    /**
     * 时间差
     * @param interval 1.相差天数 2.相差几周 3.相差几个月 4.相差几年 5.相差几小时 6.相差几分钟 7 相差几秒
     * @param begin 开始时间
     * @param end 结束时间
     * @return
     */
    public static int dateDiff(int interval, Date begin, Date end) {
        long beginTime = begin.getTime() / 1000L;
        long endTime = end.getTime() / 1000L;
        long tmp = 0L;
        if(endTime == beginTime) {
            return 0;
        } else {
            if(endTime < beginTime) {
                tmp = beginTime;
                beginTime = endTime;
                endTime = tmp;
            }

            long intervalTime = endTime - beginTime;
            long result = 0L;
            switch(interval) {
                case 1:
                    result = intervalTime / 86400L;
                    break;
                case 2:
                    result = intervalTime / 604800L;
                    break;
                case 3:
                    result = intervalTime / 2678400L;
                    break;
                case 4:
                    result = intervalTime / 31536000L;
                    break;
                case 5:
                    result = intervalTime / 3600L;
                    break;
                case 6:
                    result = intervalTime / 60L;
                    break;
                case 7:
                    result = intervalTime / 1L;
            }

            if(tmp > 0L) {
                result = 0L - result;
            }

            return (int)result;
        }
    }


    /**
     * 时间差 小数类型 s1比s2早
     * @param s1
     * @param s2
     * @return
     */
    public static double timeDifference(String s1,String s2) {
        // 定义时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        // 解析时间字符串为LocalDateTime对象
        LocalDateTime time1 = LocalDateTime.parse(s1, formatter);
        LocalDateTime time2 = LocalDateTime.parse(s2, formatter);

        // 计算两个时间之间的分钟差
        long minutesDiff = ChronoUnit.MINUTES.between(time1, time2);

        // 转换为小时（带小数）
        double hoursDiff = minutesDiff / 60.0;
        BigDecimal bd = new BigDecimal(hoursDiff);
        // 四舍五入保留两位小数
        bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
        return bd.doubleValue();
    }


    /**
     * 往前推60分钟   adjustTime(timeStr, -60)
     * 往后延迟30分钟 adjustTime(timeStr, 30)
     * 调整时间的核心方法
     * @param timeStr 输入的时间字符串
     * @param minutes 调整的分钟数，正数为延迟，负数为提前
     * @return 调整后的时间字符串
     */
    public static String adjustTime(String timeStr, int minutes) {
        DateTimeFormatter DEFAULT_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        // 解析时间字符串为LocalDateTime对象
        LocalDateTime dateTime = LocalDateTime.parse(timeStr, DEFAULT_FORMATTER);
        // 调整时间
        LocalDateTime adjustedDateTime = dateTime.plusMinutes(minutes);
        // 格式化回字符串并返回
        return adjustedDateTime.format(DEFAULT_FORMATTER);
    }


    /**
     * 判断Date a是否在Date b的正负30分钟范围内
     * @param a 日期a
     * @param b 日期b
     * @return 如果在范围内返回true，否则返回false
     */
    public static boolean isWithin30Minutes(Date a, Date b) {
        // 空值判断
        if (a == null || b == null) {
            return false;
        }

        // 计算两个日期的时间差（毫秒）
        long timeDiff = Math.abs(a.getTime() - b.getTime());

        // 30分钟对应的毫秒数：30 * 60 * 1000 = 1,800,000
        long thirtyMinutesInMs = 30 * 60 * 1000L;

        // 判断时间差是否在30分钟以内
        return timeDiff <= thirtyMinutesInMs;
    }


    /**
     * 相差多少年 (小数)
     * @return
     */
    public static double yearDiff(Timestamp start, Date end) {

        // 转换为LocalDate（使用系统默认时区）

        // 也可以指定特定时区，例如UTC
        LocalDate startDate = start.toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDate();
        LocalDate endDate = end.toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDate();

        // 确保开始日期在结束日期之前
        if (startDate.isAfter(endDate)) {
            LocalDate temp = startDate;
            startDate = endDate;
            endDate = temp;
        }

        // 计算完整的年数差
        Period period = Period.between(startDate, endDate);
        int fullYears = period.getYears();

        // 计算剩余的天数
        LocalDate nextAnniversary = startDate.plusYears(fullYears);
        long remainingDays = ChronoUnit.DAYS.between(nextAnniversary, endDate);

        // 计算剩余天数占一年的比例（使用结束日期所在年的总天数）
        int daysInYear = endDate.lengthOfYear();
        double partialYear = (double) remainingDays / daysInYear;
        // 总年数 = 完整年数 + 部分年数
        return fullYears + partialYear;
    }



    public static int getTodayYear() {
        int yyyy = Integer.parseInt(dateFormat(new Date(), "yyyy"));
        return yyyy;
    }

    public static Date getNow() {
        return new Date();
    }

    public static String dateFormatRss(Date date) {
        return date != null?dateFormat(date, "E, d MMM yyyy H:mm:ss") + " GMT":"";
    }

    public static boolean betweenStartDateAndEndDate(Date startDate, Date endDate) {
        boolean bool = false;
        Date curDate = new Date();
        if(curDate.after(startDate) && curDate.before(dateAdd(1, endDate, 1))) {
            bool = true;
        }

        return bool;
    }

    public static boolean nowDateBetweenStartDateAndEndDate(Date startDate, Date endDate) {
        boolean bool = false;
        Date curDate = new Date();
        if(curDate.after(startDate) && curDate.before(endDate)) {
            bool = true;
        }

        return bool;
    }

    public static boolean nowDateAfterDate(Date date) {
        boolean bool = false;
        Date curDate = new Date();
        if(curDate.after(date)) {
            bool = true;
        }

        return bool;
    }

    public static int getBetweenTodaysStartDateAndEndDate(Date startDate, Date endDate) {
        byte betweentoday = 0;
        if(startDate == null) {
            return betweentoday;
        } else {
            if(endDate == null) {
                Calendar calendar = Calendar.getInstance();
                String year = Integer.toString(calendar.get(Calendar.YEAR));
                String month = Integer.toString(calendar.get(Calendar.MONTH) + 1);
                String day = Integer.toString(calendar.get(Calendar.DATE));
                String strtodaytime = year + "-" + month + "-" + day;
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

                try {
                    endDate = formatter.parse(strtodaytime);
                } catch (ParseException var10) {
                    var10.printStackTrace();
                }
            }

            int betweentoday1;
            if(endDate.after(startDate)) {
                betweentoday1 = (int)((endDate.getTime() - startDate.getTime()) / 86400000L);
            } else {
                betweentoday1 = (int)((startDate.getTime() - endDate.getTime()) / 86400000L);
            }

            return betweentoday1;
        }
    }

    public static String getTime(int format) {
        StringBuffer cTime = new StringBuffer(10);
        Calendar time = Calendar.getInstance();
        int miltime = time.get(14);
        int second = time.get(13);
        int minute = time.get(12);
        int hour = time.get(11);
        int day = time.get(5);
        int month = time.get(2) + 1;
        int year = time.get(1);
        if(format != 14) {
            if(year >= 2000) {
                year -= 2000;
            } else {
                year -= 1900;
            }
        }

        if(format >= 2) {
            if(format == 14) {
                cTime.append(year);
            } else {
                cTime.append(getFormatTime(year, 2));
            }
        }

        if(format >= 4) {
            cTime.append(getFormatTime(month, 2));
        }

        if(format >= 6) {
            cTime.append(getFormatTime(day, 2));
        }

        if(format >= 8) {
            cTime.append(getFormatTime(hour, 2));
        }

        if(format >= 10) {
            cTime.append(getFormatTime(minute, 2));
        }

        if(format >= 12) {
            cTime.append(getFormatTime(second, 2));
        }

        if(format >= 15) {
            cTime.append(getFormatTime(miltime, 3));
        }

        return cTime.toString();
    }

    private static String getFormatTime(int time, int format) {
        StringBuffer numm = new StringBuffer();
        int length = String.valueOf(time).length();
        if(format < length) {
            return null;
        } else {
            for(int i = 0; i < format - length; ++i) {
                numm.append("0");
            }

            numm.append(time);
            return numm.toString().trim();
        }
    }

    public static int getUserAge(Date birthday) {
        if(birthday == null) {
            return 0;
        } else {
            Calendar cal = Calendar.getInstance();
            if(cal.before(birthday)) {
                return 0;
            } else {
                int yearNow = cal.get(1);
                cal.setTime(birthday);
                int yearBirth = cal.get(1);
                return yearNow - yearBirth;
            }
        }
    }

    public static Date getDateByUnixTime(int unixTime) {
        return new Date((long)unixTime * 1000L);
    }

    public static long getUnixTimeLong() {
        return (long)getUnixTimeByDate(new Date());
    }

    public static int getCurrentUnixTime() {
        return getUnixTimeByDate(new Date());
    }

    public static int getUnixTimeByDate(Date date) {
        return (int)(date.getTime() / 1000L);
    }

    public static long getUnixTimeLong(Date date) {
        return date.getTime() / 1000L;
    }

    public static Date getNextDay(Date date) {
        long time = date.getTime() / 1000L + 86400L;
        date.setTime(time * 1000L);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

        try {
            date = format.parse(format.format(date));
        } catch (Exception var5) {
            System.out.println(var5.getMessage());
        }

        return date;
    }

    public static Date nextDay(Date date) {
        Date newDate = (Date)date.clone();
        long time = newDate.getTime() / 1000L + 86400L;
        newDate.setTime(time * 1000L);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

        try {
            newDate = format.parse(format.format(newDate));
        } catch (Exception var6) {
            System.out.println(var6.getMessage());
        }

        return newDate;
    }

    public static Date getNowTime() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        String dateStr = dateFormat(date);

        try {
            date = format.parse(dateStr);
        } catch (ParseException var4) {
            var4.printStackTrace();
        }

        return date;
    }

    public static Date getTomorrow(Date date1) {
        Calendar now = Calendar.getInstance();
        now.setTime(date1);
        now.add(5, 1);
        return now.getTime();
    }

    public static Date getWeekAgo(Date date) {
        Date newDate = (Date)date.clone();
        long time = newDate.getTime() / 1000L - 604800L;
        newDate.setTime(time * 1000L);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

        try {
            newDate = format.parse(format.format(newDate));
        } catch (Exception var6) {
            System.out.println(var6.getMessage());
        }

        return newDate;
    }

    public static Date getDatebyTime(Date date, int n) {
        String str = dateFormat(date, "yyyy-MM-dd");
        String[] strs = StringUtils.split(str, "-");
        int month = Integer.parseInt(strs[1]);
        int monthnow = (month + n) % 12;
        int year = Integer.parseInt(strs[0]) + (month + n) / 12;
        str = year + "-" + monthnow + "-" + strs[2];
        return dateFormat(str, "yyyy-MM-dd");
    }

    public static Date yesterday(Date date) {
        Date newDate = (Date)date.clone();
        long time = newDate.getTime() / 1000L - 86400L;
        newDate.setTime(time * 1000L);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

        try {
            newDate = format.parse(format.format(newDate));
        } catch (Exception var6) {
            System.out.println(var6.getMessage());
        }

        return newDate;
    }

    public static Date getYesterday(Date date) {
        long time = date.getTime() / 1000L - 86400L;
        date.setTime(time * 1000L);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

        try {
            date = format.parse(format.format(date));
        } catch (Exception var5) {
            System.out.println(var5.getMessage());
        }

        return date;
    }

    public static String getStringNowTime() {
        Date date = new Date();
        String dateStr = dateFormat(date);
        return dateStr;
    }

    public static long getSpecifyTimeSec(long time, int range) {
        Date date = new Date((time * 1000L + 28800000L) / 86400000L * 86400000L - 28800000L);
        long zeroTime = date.getTime() / 1000L;
        long specifyTime = (long)(range * 24 * 3600);
        return zeroTime + specifyTime;
    }

    public static String formatDateByUnixTime(long unixTime, String dateFormat) {
        return dateFormat(new Date(unixTime * 1000L), dateFormat);
    }

    public static Date convertToDate(String input) {
        Date date = null;
        if(null == input) {
            return null;
        } else {
            Iterator var2 = dateFormats.iterator();

            while(var2.hasNext()) {
                SimpleDateFormat format = (SimpleDateFormat)var2.next();

                try {
                    format.setLenient(false);
                    date = format.parse(input);
                } catch (ParseException var5) {
                    ;
                }

                if(date != null) {
                    break;
                }
            }

            return date;
        }
    }

    public static Long getTodayTime() {
        Calendar today = Calendar.getInstance();
        today.set(11, 0);
        today.set(12, 0);
        today.set(13, 0);
        return Long.valueOf(String.valueOf(today.getTimeInMillis()).substring(0, 10));
    }

    public static Long getYesterdayTime() {
        Calendar today = Calendar.getInstance();
        today.set(11, -24);
        today.set(12, 0);
        today.set(13, 0);
        return Long.valueOf(String.valueOf(today.getTimeInMillis()).substring(0, 10));
    }

    public static Long getTomorrowTime() {
        Calendar tomorrow = Calendar.getInstance();
        tomorrow.set(11, 24);
        tomorrow.set(12, 0);
        tomorrow.set(13, 0);
        return Long.valueOf(String.valueOf(tomorrow.getTimeInMillis()).substring(0, 10));
    }

    public static Date getDateBegin(){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        Date start = calendar.getTime();
        return start;
    }


    public static Date getDateEnd(){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR_OF_DAY,23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        Date end = calendar.getTime();
        return end;
    }

    /**
     * 时间推移多少天
     * @param d
     * @param date
     * @return
     */
    public static Date addDay(int d,Date date){
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(calendar.DATE,d);//把日期往后增加一天.整数往后推,负数往前移动
        date=calendar.getTime();   //这个时间就是日期往后推一天的结果
        return date;
    }

    public static void main(String args[]){
        try {
            List<Date> startAndEndOfWeek = DateKit.getStartAndEndOfWeek(2025, 45);
            System.out.println(DateKit.dateFormat(startAndEndOfWeek.get(0)));
            System.out.println(DateKit.dateFormat(startAndEndOfWeek.get(1)));
        } catch (Exception e) {
            // TODO Auto-generated catch block
          e.printStackTrace();
        }
    }

    /**
     * 获取两个时间相差的天数，精确到时分秒
     * @param fDate
     * @param oDate
     * @return
     */
    public static int getIntervalDays(Date fDate, Date oDate) {

        if (null == fDate || null == oDate) {

            return -1;

        }

        long intervalMilli = Math.abs(oDate.getTime() - fDate.getTime());

        return (int) (intervalMilli / (24 * 60 * 60 * 1000));

    }


    /**
     * 获取两个时间相差的天数，精确到时分秒
     * @param fDate
     * @param oDate
     * @return
     */
    public static int getIntervalDaysNoAbs(Date fDate, Date oDate) {

        if (null == fDate || null == oDate) {

            return -1;

        }

        long intervalMilli = oDate.getTime() - fDate.getTime();

        return (int) (intervalMilli / (24 * 60 * 60 * 1000));

    }

    /**
     * 获取一周中当前日期是星期几（0~6星期1到日）
     * @param day
     * @return
     */
    public static String getWeekOfDay(int day){
        if(day<0 || day>6){
            return null;
        }

        SimpleDateFormat simdf = new SimpleDateFormat("yyyy-MM-dd");

        Calendar cal = Calendar.getInstance();
        System.out.println("现在时间："+simdf.format(cal.getTime()));
        //分别获取年、月、日
        System.out.println("年："+cal.get(cal.YEAR));
        System.out.println("月："+(cal.get(cal.MONTH)+1));//老外把一月份整成了0，翻译成中国月份要加1
        System.out.println("日："+cal.get(cal.DATE));

        cal.set(cal.DAY_OF_WEEK, cal.MONDAY);
        String weekhand = simdf.format(cal.getTime());
        System.out.println("当前时间所在周周一日期："+weekhand);
        //cal.set(cal.DAY_OF_WEEK, cal.SUNDAY);这个不符合中国人的时间观，老外把上周周日定为一周的开始。

        cal.set(Calendar.DATE, cal.get(cal.DATE) + day);
        String weeklast = simdf.format(cal.getTime());
        System.out.println("当前时间所在周周日日期："+weeklast);
        return weeklast;
    }



    public static String getDatePoor(Date endDate, Date nowDate) {

        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }



    /**
     * 获取上周一时间
     */
    public static Date getLastWeekMonday(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(getThisWeekMonday(date));
        cal.add(Calendar.DATE, -7);
        return cal.getTime();
    }

    /**
     * 获取本周一时间
     */
    public static Date getThisWeekMonday(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        // 获得当前日期是一个星期的第几天
        int dayWeek = cal.get(Calendar.DAY_OF_WEEK);
        if (1 == dayWeek) {
            cal.add(Calendar.DAY_OF_MONTH, -1);
        }
        // 设置一个星期的第一天，按中国的习惯一个星期的第一天是星期一
        cal.setFirstDayOfWeek(Calendar.MONDAY);
        // 获得当前日期是一个星期的第几天
        int day = cal.get(Calendar.DAY_OF_WEEK);
        // 根据日历的规则，给当前日期减去星期几与一个星期第一天的差值
        cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);
        return cal.getTime();
    }


    /**
     * 获取本月第一天
     * @return
     */
    public static  Date getmindate(){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));

        return calendar.getTime();
    }

    //获取上个月第一天
    public static Date getLastMonthBegin() {
        Date date = new Date();
        date.setDate(1);
        date.setHours(0);
        date.setMinutes(0);
        date.setSeconds(0);
        if (date.getMonth() - 1 <= 0) {
            date.setYear(date.getYear() - 1);
            date.setMonth(12);
        } else {
            date.setMonth(date.getMonth() - 1);
        }
        return date;
    }

    //获取上个月第一天
    public static Date getLastMonthBegin(Date date) {
        date.setDate(1);
        date.setHours(0);
        date.setMinutes(0);
        date.setSeconds(0);
        if (date.getMonth() - 1 <= 0) {
            date.setYear(date.getYear() - 1);
            date.setMonth(12);
        } else {
            date.setMonth(date.getMonth() - 1);
        }
        return date;
    }

    public static Date getLastYear() {
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.YEAR, -1);
        Date y = c.getTime();
        return y;
    }




    private static void setMinTime(Calendar calendar){
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
    }

    private static void setMaxTime(Calendar calendar){
        calendar.set(Calendar.HOUR_OF_DAY, calendar.getActualMaximum(Calendar.HOUR_OF_DAY));
        calendar.set(Calendar.MINUTE, calendar.getActualMaximum(Calendar.MINUTE));
        calendar.set(Calendar.SECOND, calendar.getActualMaximum(Calendar.SECOND));
        calendar.set(Calendar.MILLISECOND, calendar.getActualMaximum(Calendar.MILLISECOND));
    }

        /**
         * 获得该月第一天
         * @param year
         * @param month
         * @return
         */
    public static String getFirstDayOfMonth(int year,int month){
        Calendar cal = Calendar.getInstance();
        //设置年份
        cal.set(Calendar.YEAR,year);
        //设置月份
        cal.set(Calendar.MONTH, month-1);
        //获取某月最小天数
        int firstDay = cal.getActualMinimum(Calendar.DAY_OF_MONTH);
        //设置日历中月份的最小天数
        cal.set(Calendar.DAY_OF_MONTH, firstDay);
        //格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String firstDayOfMonth = sdf.format(cal.getTime());
        return firstDayOfMonth;
    }

    /**
     * 获得该月最后一天
     * @param year
     * @param month
     * @return
     */
    public static String getLastDayOfMonth(int year,int month){
        Calendar cal = Calendar.getInstance();
        //设置年份
        cal.set(Calendar.YEAR,year);
        //设置月份
        cal.set(Calendar.MONTH, month-1);
        //获取某月最大天数
        int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        //设置日历中月份的最大天数
        cal.set(Calendar.DAY_OF_MONTH, lastDay);
        //格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String lastDayOfMonth = sdf.format(cal.getTime());
        return lastDayOfMonth;
    }


    /**
     *将字符串格式yyyyMMdd的字符串转为日期，格式"yyyy-MM-dd"
     *
     * @param date 日期字符串
     * @return 返回格式化的日期
     * @throws ParseException 分析时意外地出现了错误异常
     */
    public static String strToDateFormat(String date,String dateFormat,String simpleFormat) throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat(simpleFormat);
        formatter.setLenient(false);
        Date newDate= formatter.parse(date);
        if(UtilValidate.isEmpty(dateFormat)){
            dateFormat = "yyyy-MM-dd";
        }
        formatter = new SimpleDateFormat(dateFormat);
        return formatter.format(newDate);
    }


    public static String getWeekday(String date) {// 必须yyyy-MM-dd
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdw = new SimpleDateFormat("E");
        Date d = null;
        try {
            d = sd.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sdw.format(d);
    }

    // 2，返回数字
    public static int dayForWeek(String pTime) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.setTime(format.parse(pTime));
        int dayForWeek = 0;
        if (c.get(Calendar.DAY_OF_WEEK) == 1) {
            dayForWeek = 7;
        } else {
            dayForWeek = c.get(Calendar.DAY_OF_WEEK) - 1;
        }
        return dayForWeek;
    }

    /**
     * 计算两个Date相隔的时间差
     * @param begin
     * @param end
     * @param type 0计算相差的天时分 1计算相差的天时分秒 2计算相差的时分秒
     * @return
     */
    public static JSONObject getTimeDifference(Date begin, Date end, int type) {
        JSONObject jsonObject = new JSONObject();
        int surplusDays, surplusHours, surplusMinutes, surplusSeconds;
        switch (type) {
            case 0:
                surplusDays = dateDiff(1, begin, end);
                jsonObject.put("surplusDays", surplusDays);
                surplusHours = dateDiff(5, begin, end);
                jsonObject.put("surplusHours", surplusHours - surplusDays * 24);
                surplusMinutes = dateDiff(6, begin, end) - surplusHours * 60;
                jsonObject.put("surplusMinutes", surplusMinutes);
                break;
            case 1:
                surplusDays = dateDiff(1, begin, end);
                jsonObject.put("surplusDays", surplusDays);
                surplusHours = dateDiff(5, begin, end);
                jsonObject.put("surplusHours", surplusHours - surplusDays * 24);
                surplusMinutes = dateDiff(6, begin, end) - surplusHours * 60;
                jsonObject.put("surplusMinutes", surplusMinutes);
                surplusSeconds = dateDiff(7, begin, end) - surplusHours * 3600 - surplusMinutes * 60;
                jsonObject.put("surplusSeconds", surplusSeconds);
                break;
            case 2:
                surplusHours = dateDiff(5, begin, end);
                jsonObject.put("surplusHours", surplusHours);
                surplusMinutes = dateDiff(6, begin, end) - surplusHours * 60;
                jsonObject.put("surplusMinutes", surplusMinutes);
                surplusSeconds = dateDiff(7, begin, end) - surplusHours * 3600 - surplusMinutes * 60;
                jsonObject.put("surplusSeconds", surplusSeconds);
                break;
        }
        return jsonObject;
    }
    /**
     * 获取当年的第一天
     * @return
     */
    public static Date getCurrYearFirst(){
        Calendar currCal=Calendar.getInstance();
        int currentYear = currCal.get(Calendar.YEAR);
        return getYearFirst(currentYear);
    }

    /**
     * 获取当年的最后一天
     * @return
     */
    public static Date getCurrYearLast(){
        Calendar currCal=Calendar.getInstance();
        int currentYear = currCal.get(Calendar.YEAR);
        return getYearLast(currentYear);
    }

    /**
     * 获取某年第一天日期
     * @param year 年份
     * @return Date
     */
    public static Date getYearFirst(int year){
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        Date currYearFirst = calendar.getTime();
        return currYearFirst;
    }

    /**
     * 获取某年最后一天日期
     * @param year 年份
     * @return Date
     */
    public static Date getYearLast(int year){
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        calendar.roll(Calendar.DAY_OF_YEAR, -1);
        Date currYearLast = calendar.getTime();

        return currYearLast;
    }

    public static Date getAddDayDate(Date date, int index) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(Calendar.DAY_OF_MONTH, index);
        return c.getTime();
    }


    /**
     * 判断当前时间是否在8:00到19:00之间
     * @return true表示在范围内，false表示不在
     */
    public static boolean isBetween8And19() {
        // 获取当前时间
        LocalTime now = LocalTime.now();

        // 定义8点和19点
        LocalTime start = LocalTime.of(8, 0);   // 8:00
        LocalTime end = LocalTime.of(19, 0);    // 19:00

        // 判断当前时间是否在[8:00, 19:00)区间内
        // isAfter() 表示大于，isBefore() 表示小于
        return now.isAfter(start) && now.isBefore(end)
                || now.equals(start);  // 包含8:00整的情况
    }

    /**
     * 将 LocalDate转换为date 最小数
     * @param localDate
     * @return
     */
    public static Date parseLocalDateToDateMin(LocalDate localDate) {
        // 步骤1：补充时间（默认当天00:00:00）
        LocalDateTime localDateTime = localDate.atTime(LocalTime.MIN); // 等同于 atTime(0, 0, 0)

        // 步骤2：指定时区（这里用系统默认时区，也可显式指定如 ZoneId.of("Asia/Shanghai")）
        ZoneId zoneId = ZoneId.systemDefault();

        // 步骤3：转换为Date
        Date date = Date.from(localDateTime.atZone(zoneId).toInstant());
        return date;
    }

    /**
     * 将 LocalDate转换为date 最大数
     * @param localDate
     * @return
     */
    public static Date parseLocalDateToDateMax(LocalDate localDate) {
        // 步骤1：补充时间（默认当天23:59:59）
        LocalDateTime localDateTime = localDate.atTime(LocalTime.MAX); // 等同于 atTime(0, 0, 0)

        // 步骤2：指定时区（这里用系统默认时区，也可显式指定如 ZoneId.of("Asia/Shanghai")）
        ZoneId zoneId = ZoneId.systemDefault();

        // 步骤3：转换为Date
        Date date = Date.from(localDateTime.atZone(zoneId).toInstant());
        return date;
    }
    /**
     * 根据年份和周数获取对应周一的日期
     * @param year 年份
     * @param week 周数（1-53）
     * @return 周一的LocalDate对象
     */
//    public static LocalDate getMondayOfWeek(int year, int week) {
//        // 获取当年第1周的第一天（可能是上一年的日期）
//        LocalDate firstDayOfYear = LocalDate.of(year, 1, 1);
//        LocalDate firstDayOfFirstWeek = firstDayOfYear.with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY));
//
//        // 若1月1日所在周包含当年天数不足4天，则第一周从下一周开始
//        if (firstDayOfYear.getDayOfWeek().getValue() > 4) {
//            firstDayOfFirstWeek = firstDayOfFirstWeek.plusWeeks(1);
//        }
//
//        // 计算目标周的周一
//        return firstDayOfFirstWeek.plusWeeks(week - 1);
//    }
//
//    /**
//     * 根据年份和周数获取对应周日的日期
//     * @param year 年份
//     * @param week 周数（1-53）
//     * @return 周日的LocalDate对象
//     */
//    public static LocalDate getSundayOfWeek(int year, int week) {
//        // 周一加6天即为周日
//        return getMondayOfWeek(year, week).plusDays(6);
//    }


    /**
     * 传入周别  获取这周的第一天(周1)  和 最后一天(周日)
     * @param year
     * @param week
     * @return
     */
    public static List<Date> getStartAndEndOfWeek(int year, int week){

        // 1. 获取当年第1周的第一天（ISO周历中，每周从周一开始）
        LocalDate firstDayOfYear = LocalDate.of(year, 1, 1);
        LocalDate firstDayOfFirstWeek = firstDayOfYear.with(
                TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY)
        );

        // 2. 计算目标周的周一（第1周的周一 + (周数-1)*7天）
        LocalDate monday = firstDayOfFirstWeek.plusWeeks(week - 1);

        // 3. 计算目标周的周日（周一 + 6天）
        LocalDate sunday = monday.plusDays(6);

        List<Date> dates = new ArrayList<>();
        dates.add(parseLocalDateToDateMin(monday));
        dates.add(parseLocalDateToDateMax(sunday));
        return dates;
    }







}
